package de.dopichaj.labrador.index;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.Writer;

import de.dopichaj.labrador.util.Configuration;
import de.dopichaj.labrador.util.io.ByteReader;
import de.dopichaj.labrador.util.io.DataInputToByteReaderAdapter;


/**
 * An index that is stored in the file system.
 */
public abstract class FileSystemIndex extends Index {

    protected final File indexDirectory;
    private final File versionFile;
    private final File dirtyFile;
    private int documentCount;
    private int elementCount;
    private long elementLengthSum;

    private FileSystemIndex(String[] stopWords, File indexDirectory,
        Configuration configuration) {
        
        super(stopWords, configuration);
        this.indexDirectory = indexDirectory;
        this.versionFile = new File(indexDirectory, "de.dopichaj.labrador.index-version");
        this.dirtyFile = new File(indexDirectory, "dirty");
    }

    /**
     * Create and open an index.
     * @param stopWords  The list of stop words to use. 
     * @param indexDirectory  Where the index is to be stored.
     */
    public FileSystemIndex(File indexDirectory, String[] stopWords,
        Configuration configuration) throws IOException {
        this(stopWords, indexDirectory, configuration);
        
        OutputStream indexStopWordFile =
            new FileOutputStream(new File(indexDirectory, "stopwords"));
        PrintWriter w = new PrintWriter(indexStopWordFile);
        try {
            for (int i = 0; i < stopWords.length; i++) {
                w.println(stopWords[i]);
            }
        } finally {        
            w.close();
        }
        
        this.documentCount = 0;
        this.elementCount = 0;
        this.elementLengthSum = 0;
        
        writeIndexVersion();
    }

    /**
     * Open an existing index for reading or updating.
     * @param indexDirectory
     * @throws IOException  if the stop words cannot be read.
     * @throws IndexVersionException if the existing index is in the wrong format.
     */
    public FileSystemIndex(File indexDirectory) throws IOException, IndexVersionException {
        this(getStopWords(new File(indexDirectory, "stopwords")), indexDirectory,
            new Configuration(new FileInputStream(new File(indexDirectory, "config"))));
        ensureIndexIsCurrent();
        
        final BufferedReader reader = new BufferedReader(new FileReader(getMetaDataFile()));
        try {
            documentCount = Integer.parseInt(reader.readLine());
            elementCount = Integer.parseInt(reader.readLine());
            elementLengthSum = Long.parseLong(reader.readLine());
            reader.close();
        } catch (NumberFormatException e) {
            throw new IOException("Metadata file is corrupt: " + e);
        }        
    }

    protected File getConfigurationFile() {
        return new File(indexDirectory, "config");
    }

    /**
     * Gets a stop-word-list from the index directory.
     * 
     * @return An array consisting of stop-words.
     * @throws IOException
     */
    private static String[] getStopWords(File stopWordFile) throws IOException {
        InputStream stopWordIS = new FileInputStream(stopWordFile);
        
        if(stopWordIS == null) throw new IOException("Stop word file not found!");
        
        DataInputStream in = new DataInputStream(stopWordIS);
        byte[] b;
        try {
            b = new byte[in.available()];
            in.readFully(b);
        } finally {
            in.close();
        }
        String result = new String(b, 0, b.length);
        return result.split("\n");
    }

    /**
     * Returns the index version supported by this index.
     */
    public abstract String getIndexVersion();

    /**
     * Write the version of the index.
     * @throws IOException
     */
    private void writeIndexVersion() throws IOException {
        Writer writer = new OutputStreamWriter(new FileOutputStream(versionFile));
        try {
            writer.write(getIndexVersion());
        } finally {
            writer.close();
        }
    }
    
    /**
     * Ensure that the index is compatible with the current implementation.
     * 
     * @throws IndexVersionException
     */
    private void ensureIndexIsCurrent() throws IndexVersionException {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                new FileInputStream(versionFile)));
            String version = reader.readLine();
            reader.close();
            if (version == null) {
                throw new IndexVersionException("Index version file exists, " +
                    "but contains no de.dopichaj.labrador.index version information.");
            }
            if (!version.equals(getIndexVersion())) {
                throw new IndexVersionException("Index is version " + version +
                    " (need " + getIndexVersion() + ")");
            }
        } catch (FileNotFoundException e) {
            throw new IndexVersionException("Index version file not found", e);
        } catch (IOException e) {
            throw new IndexVersionException("Cannot read de.dopichaj.labrador.index version file", e);
        }
    }

    @Override
    public boolean isDirty() {
        return dirtyFile.exists();
    }
    
    @Override
    public void markAsDirty() throws FileNotFoundException {
        PrintWriter dirtyWriter = new PrintWriter(new FileOutputStream(dirtyFile));
        dirtyWriter.println("Marker that the de.dopichaj.labrador.index is dirty. Delete at your own risk.");
        dirtyWriter.close();
    }
    
    @Override
    public void markAsClean() {
        dirtyFile.delete();
    }

    private File getTagIdFile() {
        return new File(indexDirectory, "tagidmap");
    }
    
    @Override
    public BufferedReader getTagIdReader() throws FileNotFoundException {
        return new BufferedReader(new FileReader(getTagIdFile()));
    }

    @Override
    public PrintWriter getTagIdWriter() throws FileNotFoundException {
        
        return new PrintWriter(new FileOutputStream(getTagIdFile(), true));
    }

    private File getDigestFile() {
        return new File(indexDirectory, "digest");
    }
    
    @Override
    public ByteReader getDigestByteReader() throws FileNotFoundException {
        return new DataInputToByteReaderAdapter(new RandomAccessFile(getDigestFile(), "r"));
    }

    @Override
    public OutputStream getDigestOutputStream() throws FileNotFoundException {
        return new FileOutputStream(getDigestFile());
    }

    private File getMetaDataFile() {
        return new File(indexDirectory, "metadata");
    }
    
    @Override
    public void storeMetaData(int documentCount, int elementCount, long elementLengthSum) throws IOException {
        
        final PrintWriter writer = new PrintWriter(new FileWriter(getMetaDataFile()));
        writer.print(documentCount);
        writer.println();
        writer.print(elementCount);
        writer.println();
        writer.print(elementLengthSum);
        writer.println();
        writer.close();
    }

    @Override
    public int getDocumentCount() {
        return documentCount;
    }

    @Override
    public int getElementCount() {
        return elementCount;
    }

    @Override
    public long getElementLengthSum() {
        return elementLengthSum;
    }
}
/*
Copyright (c) 2007 Philipp Dopichaj

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/